package com.ruoyi.tools.util.http;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.tools.util.json.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;


@Component
public class BackEndHttpRequest{

	public static void main(String[] args) {
//		String str2=BackEndHttpRequest.sendJpGet("https://api.mercari.jp/items/get?id=m48682567174", "");
//		Map maps = (Map) JSONObject.parseObject(str2);
//		Map data = (Map)JSONObject.parseObject(maps.get("data").toString());
//		Map seller = (Map)JSONObject.parseObject(data.get("seller").toString());
//		System.out.println(seller.get("id"));
//		String myString = "core/pages/viewemployee.jsff";
//		String newString = myString.substring(myString.lastIndexOf("/")+1, myString.length());
//		System.out.println(newString);

		String newurl = "https://api.mercari.jp/items/get?id=m57552114305";
		System.out.println(newurl);
		//String str2= BackEndHttpRequest.sendJpGet(newurl, "");
		//System.out.println(str2);
	}
	@Autowired
    private static BackEndHttpRequest p2;
	
	@PostConstruct
    public void init() {
        p2 = this;
    }



	/**
	 * 向指定的URL发送GET方法的请求
	 * @param url    发送请求的URL
	 * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式
	 * @return       远程资源的响应结果
	 */
	public static String sendJpGet(String url, String param,String drop) {
		String result = "";
		BufferedReader bufferedReader = null;
		try {
			//1、读取初始URL
			String urlNameString = url;
			//2、将url转变为URL类对象
			URL realUrl = new URL(urlNameString);

			//3、打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			//4、设置通用的请求属性
			connection.setRequestProperty("dpop", drop);
			connection.setRequestProperty("x-platform", "web");

			//5、建立实际的连接
			connection.connect();
			//获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			//遍历所有的响应头字段
			for(String key : map.keySet()) {
				System.out.println(key + "---->" + map.get(key));
			}

			//6、定义BufferedReader输入流来读取URL的响应内容 ，UTF-8是后续自己加的设置编码格式，也可以去掉这个参数
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line = "";
			while(null != (line = bufferedReader.readLine())) {
				result += line;
			}
//			int tmp;
//            while((tmp = bufferedReader.read()) != -1){
//                result += (char)tmp;
//            }

		}catch (Exception e) {
			// TODO: handle exception
			System.out.println("发送GET请求出现异常！！！"  + e);
			e.printStackTrace();
		}finally {        //使用finally块来关闭输入流
			try {
				if(null != bufferedReader) {
					bufferedReader.close();
				}
			}catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定的URL发送GET方法的请求
	 * @param url    发送请求的URL
	 * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式 
	 * @return       远程资源的响应结果 
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader bufferedReader = null;
		try {
			//1、读取初始URL
			String urlNameString = url + "?" + param;
			//2、将url转变为URL类对象
			URL realUrl = new URL(urlNameString);
			
			//3、打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			//4、设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			//connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			//5、建立实际的连接 
			connection.connect();
			//获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			//遍历所有的响应头字段
			for(String key : map.keySet()) {
				System.out.println(key + "---->" + map.get(key));
			}
			
			//6、定义BufferedReader输入流来读取URL的响应内容 ，UTF-8是后续自己加的设置编码格式，也可以去掉这个参数
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line = "";
			while(null != (line = bufferedReader.readLine())) {
				result += line;
			}
//			int tmp;
//            while((tmp = bufferedReader.read()) != -1){
//                result += (char)tmp;
//            }
			
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println("发送GET请求出现异常！！！"  + e);
			e.printStackTrace();
		}finally {        //使用finally块来关闭输入流 
			try {
				if(null != bufferedReader) {
					bufferedReader.close();
				}
			}catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * 向指定的URL发送POST方法的请求
	 * @param url    发送请求的URL
	 * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式 
	 * @return       远程资源的响应结果 
	 */
	public static String sendPost(String url, String param) {
		String result = "";
		BufferedReader bufferedReader = null;
		PrintWriter out = null;
		try {
			//1、2、读取并将url转变为URL类对象
			URL realUrl = new URL(url);
			
			//3、打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			//4、设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			
			// 发送POST请求必须设置如下两行  
			connection.setDoInput(true);
			connection.setDoOutput(true);
			
			//5、建立实际的连接
			//connection.connect();
			//获取URLConnection对象对应的输出流
			out = new PrintWriter(connection.getOutputStream());
			//发送请求参数
			out.print(param);
			//flush输出流的缓冲
			out.flush();
			//
			
			//6、定义BufferedReader输入流来读取URL的响应内容
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line;
			while(null != (line = bufferedReader.readLine())) {
				result += line;
			}
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println("发送POST请求出现异常！！！"  + e);
			e.printStackTrace();
		}finally {        //使用finally块来关闭输出流、输入流 
			try {
				if(null != out) {
					out.close();
				}
				if(null != bufferedReader) {
					bufferedReader.close();
				}
			}catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定的URL发送POST方法的请求
	 * @param defURL    发送请求的URL
	 * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式
	 * @return       远程资源的响应结果
	 */
	public static String sendPostjson(String defURL, JSONObject param) {
		StringBuffer sbf = new StringBuffer();
		URL url = null;
		try {
			url = new URL(defURL);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		// 打开和URL之间的连接
		HttpURLConnection con = null;
		try {
			con = (HttpURLConnection)url.openConnection();
			con.setRequestMethod("POST");//请求post方式
			con.setUseCaches(false); // Post请求不能使用缓存
			con.setDoInput(true);// 设置是否从HttpURLConnection输入，默认值为 true
			con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出，默认值为 false

			//设置header内的参数 connection.setRequestProperty("健, "值");
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestProperty("isTree", "true");
			con.setRequestProperty("isLastPage", "true");

			//设置body内的参数，put到JSONObject中
			// 建立实际的连接
			con.connect();
			// 得到请求的输出流对象
			OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
			writer.write(JsonUtils.ObjectToString(param));
			writer.flush();
			// 获取服务端响应，通过输入流来读取URL的响应
			InputStream is = con.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();

			// 关闭连接
			con.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sbf.toString();
	}
}
